package com.che.software.testato.web.controller;

import java.io.Serializable;
import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.che.software.testato.business.ServiceManager;
import com.che.software.testato.business.UserManager;
import com.che.software.testato.business.exception.ServiceSearchManagerException;
import com.che.software.testato.business.exception.UserSearchManagerException;
import com.che.software.testato.domain.entity.User;
import com.che.software.testato.domain.entity.search.UserSearch;
import com.che.software.testato.web.controller.acontroller.AbstractController;

/**
 * Controller used to manage the current session.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractController, Serializable.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Component("sessionController")
@ManagedBean(name = "sessionController")
@Scope("session")
@SessionScoped
public class SessionController extends AbstractController implements Serializable {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(SessionController.class);
	private static final long serialVersionUID = 7865189106125014901L;

	/**
	 * Members.
	 */
	@Autowired
	private transient ServiceManager serviceManager;
	private User sessionUser;
	@Autowired
	private transient UserManager userManager;

	/**
	 * Retrieve the current date.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @return the current date.
	 * @since July, 2011.
	 */
	public Date getCurrentTimestamp() {
		LOGGER.debug("getCurrentTimestamp().");
		return new Date();
	}

	/**
	 * Getter for the private field value userManager.
	 * 
	 * @return the userManager field value.
	 */
	public UserManager getUserManager() {
		return userManager;
	}

	/**
	 * Setting a value to the userManager field.
	 * 
	 * @param userManager the value to set.
	 */
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/**
	 * Getter for the private field value sessionUser.
	 * 
	 * @return the sessionUser field value.
	 */
	public User getSessionUser() {
		if (null == sessionUser) {
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			if (null != auth) {
				Object principal = auth.getPrincipal();
				if (null != principal && principal instanceof UserDetails) {
					try {
						LOGGER.debug("Loading " + ((UserDetails) principal).getUsername() + " properties.");
						sessionUser = userManager.searchUsers(new UserSearch(((UserDetails) principal).getUsername())).get(0);
						sessionUser.setService(serviceManager.searchServiceFromUserId(sessionUser.getUserId()));
					} catch (UserSearchManagerException e) {
						LOGGER.error("Error during the recovery of the user's properties.", e);
					} catch (ServiceSearchManagerException e) {
						LOGGER.error("Error during the recovery of the user's service.", e);
					}
				}
			}
		}
		return sessionUser;
	}

	/**
	 * Setting a value to the sessionUser field.
	 * 
	 * @param sessionUser the value to set.
	 */
	public void setSessionUser(User sessionUser) {
		this.sessionUser = sessionUser;
	}

	/**
	 * Getter for the private field value serviceManager.
	 * 
	 * @return the serviceManager field value.
	 */
	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	/**
	 * Setting a value to the serviceManager field.
	 * 
	 * @param serviceManager the value to set.
	 */
	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
}